package com.bwei.like.mostitemnews.view;

import android.content.Context;
import android.graphics.Color;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bwei.like.mostitemnews.R;

/**
 * Created by LiKe on 2016/11/22.
 */
public class ViewPageIndictor extends HorizontalScrollView implements View.OnClickListener, ViewPager.OnPageChangeListener {
    private ViewPager viewPager;
    private LinearLayout linearLayout;

    public ViewPageIndictor(Context context) {
        super(context);
    }

    public ViewPageIndictor(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ViewPageIndictor(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    public void setIndictor(ViewPager viewPager) {
        this.viewPager = viewPager;
        viewPager.setOnPageChangeListener(this);

        PagerAdapter adapter = viewPager.getAdapter();

        linearLayout = new LinearLayout(getContext());

        for (int i = 0; i < adapter.getCount(); i++) {
            TextView textView = new TextView(getContext());
            textView.setOnClickListener(this);
            if (i == 0) {
                textView.setTextColor(Color.RED);
            }else {
                textView.setTextColor(Color.GRAY);
            }
            textView.setText(adapter.getPageTitle(i));
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins(20,5,20,5);
            linearLayout.addView(textView,params);
        }

        this.addView(linearLayout);
    }

    @Override
    public void onClick(View v) {
        for (int i = 0; i < linearLayout.getChildCount(); i++) {
            TextView textView = (TextView) linearLayout.getChildAt(i);
            if (textView == v){
                viewPager.setCurrentItem(i);
            }
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        for(int i=0;i<linearLayout.getChildCount();i++){
            TextView textView = (TextView) linearLayout.getChildAt(i);
            if (i == position){
                textView.setTextColor(Color.RED);
            }else {
                textView.setTextColor(Color.GRAY);
            }
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
